package top.xana.acg.anime.ui.view

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.core.view.isInvisible
import top.xana.acg.anime.R

/**
 * Created by xana on 2022/1/15
 * Describe: hello world
 */
class SearchView(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) :
    FrameLayout(context, attributeSet, defStyleAttr) {
    constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
    constructor(context: Context) : this(context, null)

    val view: View
    val back: ImageView
    val inputView: EditText
    val delView: ImageView

    var kw: String? = null
    var searchListener: onSearchListener? = null

    fun setOnSearchListener(searchListener: onSearchListener) {
        this.searchListener = searchListener
    }

    init {
        view = LayoutInflater.from(context).inflate(R.layout.view_search_view, this)
        back = view.findViewById(R.id.back)
        inputView = view.findViewById(R.id.inputView)
        delView = view.findViewById(R.id.delete)
/*        inputView.setOnEditorActionListener { view, actionId, event ->
            kw = view.text.toString()
            if ((event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
                searchListener?.onSearch(kw!!)
                true;
            }
            false
        }*/
        inputView.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                kw = p0.toString()
                if(p0?.endsWith('\n') == true){
//                    hintKb(App.app(), inputView)
                    searchListener?.onSearch(kw!!)
                  //  inputView.setText("")
                }

                delView.isInvisible = p0?.length == 0
            }

            override fun afterTextChanged(p0: Editable?) {

            }

        })
        delView.setOnClickListener{
            inputView.setText("")
        }
        back.setOnClickListener{
            searchListener?.onBack()

        }
    }

    interface onSearchListener {
        fun onSearch(kw: String)
        fun onBack()
    }
}